//
function navAjax(options) {
    $.ajax({
        type: options.type == null ? "POST" : options.type,
        dataType: "json",
        data: options.data,
        contentType: options.contentType == null ? "application/json;charset=utf-8" : options.contentType,
        url: "http://120.55.165.31:8080/Elearning/api" + options.url,
        success: options.success,
        error: options.error == null ? function () {
            alert("ajax失败");
        } : options.error,
        async: options.async == null ? false : options.async
    });
}

// 获取当前用户的token
function getToken(){
    // 测试用的token 实际上token需要从会话存储中提取
    //let token = JSON.parse(sessionStorage.getItem("myData")).token;
    let token = null;
    navAjax({
        data:JSON.stringify({ username:"user", password:"123456"}),
        url: "/all/user/login",
        success: function (response) {
            token = response.data.token;
        }
    });
    console.log(token);
    return token;
}

// 获取用户信息
function getUserInfo() {
    let userInfo = null;
    let options = {
        data:JSON.stringify({token : getToken()}),
        url:"/user/user/getUserCurrent",
        success:function (response) {
            userInfo = response.data;
        }
    };
    options.data = options.data.replace('"token":','"token": ');
    navAjax(options);
    return userInfo;
}

// 获取未读消息数
function getUnreadMessageNum() {
    let number = 0;
    let options = {
        data:JSON.stringify({token : getToken(),page: "1", number:10000}),
        url:"/user/message/selectTotalUnreadMessage",
        success:function (response) {
            number = response.data.total;
        }
    };
    options.data = options.data.replace('"token":','"token": ');
    navAjax(options);
    return number;
}

// 渲染导航栏界面
function setNav(info) {
    $(".badge").text(getUnreadMessageNum());
    $("#userimg").parent().html(info.username + '<img id="userimg" alt="用户头像">')
    $("#userimg").attr("src", "http://120.55.165.31:8080/Elearning/" + info.userImage);
}

$(document).ready(function () {
    let userInfo = getUserInfo();
    setNav(userInfo);
});

function setSearchKey(){
    let keyWord = $("input[name='search-box']").val();
    sessionStorage.setItem("search-key", keyWord);
}